package demo.common.model;

import com.google.common.base.CaseFormat;
import demo.base.Join;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by llq on 2017/6/12.
 */
public class PagingCondition {

    public static final PagingCondition ALL;

    static {
        PagingCondition pagingCondition = new PagingCondition();
        pagingCondition.length = Long.MAX_VALUE;
        ALL = pagingCondition;
    }

    private Long start = 0L;
    private Long length = 10L;

    /**
     * 简单的搜索框，模糊搜索
     */
    private String search;

    /**
     * 当前用户id
     */
    private Integer currentUserId;

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    public Integer getCurrentUserId() {
        return currentUserId;
    }

    public void setCurrentUserId(Integer currentUserId) {
        this.currentUserId = currentUserId;
    }

    public Long getStart() {
        return start;
    }

    public void setStart(Long start) {
        this.start = start;
    }

    public Long getLength() {
        return length;
    }

    public void setLength(Long length) {
        this.length = length;
    }

    public String getLowerSearch() {
        if (search != null) {
            return search.toLowerCase();
        }
        return null;
    }

    public List<String> whereSQL() {
        return Collections.emptyList();
    }

    public static String eq(String propName) {
        return propertyName2TableFieldName(propName) + " = #{" + propName + "}";
    }

    public static String eq(String propName, String value) {
        return propertyName2TableFieldName(propName) + " = '" + value + "' ";
    }

    public String in(String propName, String[] values) {
        return propertyName2TableFieldName(propName) + " in (" +
                Join.join(values, ",", "'", "'") +
                ") ";
    }

    public static String propertyName2TableFieldName(String propertyName) {
        return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, propertyName);
    }

    public static String containBySearch(String... propNames) {
        List<String> sqls = new ArrayList<>();
        for (String propName : propNames) {
            sqls.add("lower(" + propertyName2TableFieldName(propName) + ") like lower(concat('%', #{search}, '%'))");
        }
        return "(" + Join.join(sqls, " or ") + ")";
    }

    public String orderSQL() {
        return "";
    }

}
